package cn.wetcland.urban.admin.service.impl;

import cn.wetcland.urban.admin.dto.OpenCityAddDTO;
import cn.wetcland.urban.admin.dto.OpenCityUpdateDTO;
import cn.wetcland.urban.admin.mapper.UtDistrictMapper;
import cn.wetcland.urban.admin.mapper.UtOpenCityMapper;
import cn.wetcland.urban.admin.service.UtOpenCityService;
import cn.wetcland.urban.common.MyAssert;
import cn.wetcland.urban.generator.domain.UtDistrict;
import cn.wetcland.urban.generator.domain.UtOpenCity;
import cn.wetcland.urban.generator.dto.BaseConditionSearchDTO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class UtOpenCityServiceImpl extends ServiceImpl<UtOpenCityMapper, UtOpenCity> implements UtOpenCityService {

    @Resource
    public UtOpenCityMapper openCityMapper;

    @Resource
    public UtDistrictMapper districtMapper;

    @Override
    public Page<UtOpenCity> openCityList(BaseConditionSearchDTO searchDTO) {
        Page<UtOpenCity> page = new Page<>(searchDTO.getCurPage(), searchDTO.getPageSize());
        return openCityMapper.selectPage(page, null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void openCityUpdate(OpenCityUpdateDTO updateDTO) {
        UtOpenCity utOpenCity = openCityMapper.selectById(updateDTO.getId());
        MyAssert.notNull(utOpenCity, "该开放城市记录不存在");
        UtDistrict district = districtMapper.selectById(updateDTO.getCityId());
        MyAssert.notNull(district, "城市不存在");
        MyAssert.isTrue(district.getLevel().equals("city"), "非城市ID");
        utOpenCity.setCityId(updateDTO.getCityId());
        utOpenCity.setCityName(district.getName());
        openCityMapper.updateById(utOpenCity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void openCityDelete(Long id) {
        openCityMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void openCityAdd(OpenCityAddDTO addDTO) {
        UtOpenCity utOpenCity = new UtOpenCity();
        UtDistrict district = districtMapper.selectById(addDTO.getCityId());
        MyAssert.notNull(district, "城市不存在");
        MyAssert.isTrue(district.getLevel().equals("city"), "非城市ID");
        utOpenCity.setCityId(addDTO.getCityId());
        utOpenCity.setCityName(district.getName());
        openCityMapper.insert(utOpenCity);
    }
}
